package se.topshelf.golftracker.web.editor;

import se.topshelf.golftracker.core.domain.BaseEntity;
import se.topshelf.golftracker.core.service.BaseService;

import java.beans.PropertyEditorSupport;

/**
 *
 */
public class BaseEntityEditor<T extends BaseEntity> extends PropertyEditorSupport{
    private Class<T> baseEntityClass;
    private BaseService baseService;

    public BaseEntityEditor(Class<T> baseEntityClass, BaseService baseService) {
        this.baseEntityClass = baseEntityClass;
        this.baseService = baseService;
    }

    @Override
    public void setValue(Object value) {
        if(value != null){
            if(value.getClass().isAssignableFrom(baseEntityClass)){
                super.setValue(value);
            }
        }else {
            super.setValue(null);
        }

    }

    @Override
    public void setAsText(String id) throws IllegalArgumentException {
        if(id == null){
            return;
        }
        setValue(baseService.get(baseEntityClass, id));
    }

    @Override
    public String getAsText() {
        if(getValue() != null){
            return ((T)getValue()).getId();
        }
        return null;
    }
}
